import datetime
import os
import logging
import subprocess

logging.basicConfig(level=logging.INFO, format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                    datefmt='%a, %d %b %Y %H:%M:%S')


class baidu_write_xiaofei_info:

    def __init__(self, baidu_xiaofei_info_single, big_channel, ys_noys, xiaofei_file):

        self.date_format = datetime.datetime.now() + datetime.timedelta(days=-1)
        self.yesterday = self.date_format.strftime('%Y-%m-%d')
        # self.xiaofei_file = "./baidu_xiaofei_info_dir/" + self.yesterday
        # 区分是百度还是推啊等
        self.xiaofei_file = xiaofei_file + self.yesterday
        self.baidu_xiaofei_info_single = baidu_xiaofei_info_single
        # 每个名字对应的文件
        self.big_channel = big_channel + "_data"
        self.quchong_file = self.big_channel + "_quchong"
        self.ys_noys = ys_noys

    def judge_dir(self, need_check_dir):

        # 判断前一天日志存储目录是否存在，不存在创建
        if not os.path.exists(need_check_dir):
            os.makedirs(need_check_dir)

        else:
            logging.info(need_check_dir + " already exists !")

    def write_file(self):

        self.judge_dir(self.xiaofei_file)
        with open(self.xiaofei_file + "/" + self.big_channel, "a", encoding='utf-8') as message_log:
            try:
                message_log.write(self.baidu_xiaofei_info_single + "\n")

            except Exception as e:
                logging.info(e)

    def read_file(self, num):

        name_password_dict = []
        subprocess.call("awk '!x[$0]++' {} > {}".format(self.xiaofei_file + "/" + self.big_channel,
                                                        self.xiaofei_file + "/" + self.quchong_file), shell=True)
        with open(self.xiaofei_file + "/" + self.quchong_file) as read_file:
            for line in read_file:
                name_password_dict.append(line.strip().split("\t")[num].strip())

        return name_password_dict

    def read_name_password(self):

        return self.read_file(num=2)

    def read_cost(self):

        return int(sum(list(map(int, self.read_file(num=1)))) / self.ys_noys)

